<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2 class="page-title">个人中心</h2>
      <p class="page-subtitle">管理您的个人信息和账户设置</p>
    </div>
    
    <div class="profile-content">
      <!-- 个人信息卡片 -->
      <el-card class="profile-card">
        <template #header>
          <div class="card-header">
            <el-icon><UserFilled /></el-icon>
            <span>用户信息</span>
          </div>
        </template>
        
        <div class="profile-info">
          <div class="avatar-container">
            <div class="avatar-wrapper" @click="showAvatarSelector = true">
              <img 
                v-if="userStore.avatar" 
                :src="userStore.avatar" 
                class="user-avatar-image"
                :alt="userStore.username || '用户头像'"
              />
              <el-avatar 
                v-else 
                :size="100" 
                class="user-avatar"
              >
                {{ userInitial }}
              </el-avatar>
              <div class="avatar-edit-overlay">
                <el-icon><Edit /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
          </div>
          
          <div class="info-details">
            <div class="info-item">
              <label>用户名：</label>
              <span class="info-value">{{ userStore.username }}</span>
            </div>
            <div class="info-item">
              <label>账户状态：</label>
              <el-tag type="success">活跃</el-tag>
            </div>
            <div class="info-item">
              <label>角色：</label>
              <span class="info-value">{{ userStore.role || '管理员' }}</span>
            </div>
            <div class="info-item">
              <label>登录时间：</label>
              <span class="info-value">{{ loginTime }}</span>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 账户设置卡片 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <el-icon><Setting /></el-icon>
            <span>账户设置</span>
          </div>
        </template>
        
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input v-model="formData.currentPassword" type="password" show-password placeholder="请输入当前密码" />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="formData.newPassword" type="password" show-password placeholder="请输入新密码" />
          </el-form-item>
          
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input v-model="formData.confirmPassword" type="password" show-password placeholder="请再次输入新密码" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleUpdatePassword" :loading="loading">修改密码</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 系统信息卡片 -->
      <el-card class="system-card">
        <template #header>
          <div class="card-header">
            <el-icon><Monitor /></el-icon>
            <span>系统信息</span>
          </div>
        </template>
        
        <div class="system-info">
          <div class="system-item">
            <label>系统版本：</label>
            <span class="info-value">v1.0.0</span>
          </div>
          <div class="system-item">
            <label>最近更新：</label>
            <span class="info-value">2023-11-20</span>
          </div>
          <div class="system-item">
            <label>技术支持：</label>
            <span class="info-value">support@device-management.com</span>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 头像选择器对话框 -->
    <el-dialog
      v-model="showAvatarSelector"
      title="选择头像"
      width="500px"
      @close="handleAvatarDialogClose"
    >
      <div class="avatar-selection">
        <div 
          v-for="avatar in availableAvatars" 
          :key="avatar.value"
          class="avatar-option"
          :class="{ 'avatar-option-selected': selectedAvatar === avatar.value }"
          @click="selectedAvatar = avatar.value"
        >
          <img :src="avatar.src" :alt="avatar.name" class="avatar-option-img" />
          <span class="avatar-option-name">{{ avatar.name }}</span>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="handleAvatarDialogClose">取消</el-button>
        <el-button type="primary" @click="confirmAvatarSelection">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, inject } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox } from 'element-plus';
import notificationService from '../utils/notificationService.js';
import { UserFilled, Setting, Monitor, Edit } from '@element-plus/icons-vue';

const router = useRouter();
const loading = ref(false);
const formRef = ref(null);
const showAvatarSelector = ref(false);
const selectedAvatar = ref('');

// 注入用户状态管理
const userStore = inject('userStore');

// 可用的头像列表
const availableAvatars = ref([
  {
    name: '头像1',
    value: 'http://14.103.171.191:8080/images/640-7.svg',
    src: 'http://14.103.171.191:8080/images/640-7.svg'
  },
  {
    name: '头像2',
    value: 'http://14.103.171.191:8080/images/640-8.svg',
    src: 'http://14.103.171.191:8080/images/640-8.svg'
  },
  {
    name: '头像3',
    value: 'http://14.103.171.191:8080/images/images.svg',
    src: 'http://14.103.171.191:8080/images/images.svg'
  }
]);

// 表单数据
const formData = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单验证规则
const rules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{6,}$/,
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 登录时间
const loginTime = ref('');

// 计算用户名首字母
const userInitial = computed(() => {
  return userStore.username ? userStore.username.charAt(0).toUpperCase() : 'U';
});

// 加载用户信息
const loadUserInfo = () => {
  try {
    // 设置当前选中的头像，处理可能的反引号和空格
    let avatarUrl = userStore.avatar;
    if (typeof avatarUrl === 'string') {
      avatarUrl = avatarUrl.replace(/[`]/g, '').trim();
    }
    selectedAvatar.value = avatarUrl || 'http://14.103.171.191:8080/images/640-8.svg';
    
    // 记录登录时间
    const now = new Date();
    loginTime.value = now.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || '加载用户信息失败'
    notificationService.error(errorMessage)
    console.error('加载用户信息失败:', error);
  }
};

// 修改密码
const handleUpdatePassword = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    // 模拟验证当前密码（实际项目中应该调用后端接口）
    if (formData.currentPassword !== 'Passw0rd') {
      // 这里不需要前端提示，将在catch块中统一处理错误信息
      return;
    }
    
    loading.value = true;
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    notificationService.success('密码修改成功，请重新登录');
    
    // 清除本地存储，重定向到登录页
    localStorage.removeItem('userInfo');
    userStore.username = '管理员';
    userStore.avatar = '';
    router.push('/login');
  } catch (error) {
    console.error('修改密码失败:', error);
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理头像对话框关闭
const handleAvatarDialogClose = () => {
  // 重置选中状态为当前用户头像
  selectedAvatar.value = userStore.avatar || 'http://14.103.171.191:8080/images/640-8.svg';
  showAvatarSelector.value = false;
};

// 确认头像选择
const confirmAvatarSelection = () => {
  try {
    // 使用全局状态管理更新头像，实现实时更新
    userStore.updateUserInfo({
      avatar: selectedAvatar.value || 'http://14.103.171.191:8080/images/640-8.svg'
    });
    
    notificationService.success('头像修改成功');
    showAvatarSelector.value = false;
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || '头像修改失败'
    notificationService.error(errorMessage)
    console.error('保存头像失败:', error);
  }
};

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  color: #303133;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.profile-card,
.settings-card,
.system-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #667eea;
}

.profile-info {
  display: flex;
  align-items: center;
  padding: 20px 0;
}

.avatar-container {
  margin-right: 40px;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
}

.avatar-wrapper:hover {
  transform: scale(1.05);
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-size: 36px;
  color: white;
}

.user-avatar-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #e6e6e6;
}

.avatar-edit-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-wrapper:hover .avatar-edit-overlay {
  opacity: 1;
}

.avatar-edit-overlay .el-icon {
  margin-bottom: 5px;
  font-size: 18px;
}

.avatar-edit-overlay span {
  font-size: 12px;
}

.info-details {
  flex: 1;
}

.info-item,
.system-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.info-item:last-child,
.system-item:last-child {
  margin-bottom: 0;
}

.info-item label,
.system-item label {
  font-size: 14px;
  color: #606266;
  width: 100px;
  flex-shrink: 0;
}

.info-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.settings-card .el-form {
  padding: 20px 0;
}

.system-info {
  padding: 20px 0;
}

/* 头像选择器样式 */
.avatar-selection {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 10px 0;
}

.avatar-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.avatar-option:hover {
  background-color: #f5f7fa;
}

.avatar-option-selected {
  border-color: #667eea;
  background-color: #eef2ff;
}

.avatar-option-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 8px;
}

.default-avatar-option {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-size: 30px;
  color: white;
  margin-bottom: 8px;
}

.avatar-option-name {
  font-size: 12px;
  color: #606266;
}

.avatar-option-selected .avatar-option-name {
  color: #667eea;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }
  
  .profile-info {
    flex-direction: column;
    text-align: center;
  }
  
  .avatar-container {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .info-item {
    justify-content: center;
  }
  
  .info-item label {
    width: auto;
    margin-right: 10px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .avatar-selection {
    justify-content: center;
  }
}
</style>